package com.cn.config;

import com.cn.constant.CacheConstant;
import com.cn.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class RedisInterceptor implements HandlerInterceptor {

    private StringRedisTemplate stringRedisTemplate;

    public RedisInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate =stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.判断是否携带token信息
        String header = request.getHeader("authorization");
        if (header==null){
            return true;
        }
        //2.判断redis中是否存在
        String cacheCode = stringRedisTemplate.opsForValue().get(CacheConstant.codeConstant +header);
        if (cacheCode==null){
            response.setStatus(401);
            return false;
        }
        //3.存在保存到ThreadLoad
        UserHolder.setUser(cacheCode);
        return true;
    }
}
